package models

import (
	"encoding/json"
	"errors"
)

type VoteData struct {
	//UserID int 从请求中获取当前的用户
	PostID    string `json:"post_id,string"`   // 帖子id
	Direction int    `json:"direction,string"` // 赞成票(1)还是反对票(-1)取消投票(0)
}

// UnmarshalJSON 为VoteData类型实现自定义的UnmarshalJSON方法
func (v *VoteData) UnmarshalJSON(data []byte) (err error) {
	required := struct {
		PostID    string `json:"post_id"`
		Direction int    `json:"direction"`
	}{}
	err = json.Unmarshal(data, &required)
	if err != nil {
		return
	} else if len(required.PostID) == 0 {
		err = errors.New("缺少必填字段post_id")
	} else if required.Direction == 0 {
		err = errors.New("缺少必填字段direction")
	} else {
		v.PostID = required.PostID
		v.Direction = required.Direction
	}
	return
}

// VoteDataForm 投票数据
type VoteDataForm struct {
	//UserID int 从请求中获取当前的用户
	PostID    string `json:"post_id" binding:"required"`              // 帖子id
	Direction int8   `json:"direction,string" binding:"oneof=1 0 -1"` // 赞成票(1)还是反对票(-1)取消投票(0)
}